<template>
<div class="container">
    <header class="header">
        <div class="header-content">
            <div class="header-left">
                <a href="#" @click="GoBack()" class="back-btn">
                    <svg t="1751614585251" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" 
                        p-id="1471" width="20" height="20">
                        <path d="M790.865959 73.216062 322.123178 512.062492l468.74278 438.746442c16.397998 16.697962 16.397998 43.894642 0 60.592603-16.397998 16.697962-42.894764 16.697962-59.292762 0l-498.839107-466.943c-8.698938-8.898914-12.398487-20.797461-11.898548-32.496033-0.599927-11.698572 3.099622-23.497132 11.898548-32.496033l498.839107-466.943c16.397998-16.697962 42.894764-16.697962 59.292762 0C807.263957 29.421409 807.263957 56.518101 790.865959 73.216062z" 
                            fill="#272636" 
                            p-id="1472">
                        </path>
                    </svg>
                </a>
                <div class="header-title">我的获赞</div>
            </div>
        </div>
    </header>

    <main class="main-content">
        <!-- 列表内容 -->
        <div class="list-container">
            <!-- 获赞记录 -->
            <div class="like-list">
                <!-- 列表内容 -->
                <div v-for="like in likeList" :key="like.id" class="like-item" @click="goToPostDetail(like.postId)">
                    <!-- 用户头像 -->
                    <div class="like-avatars" @click.stop="handleAvatarClick(like.likedUsers)">
                        <!-- 单个点赞用户 -->
                        <div v-if="like.likedUsers && like.likedUsers.length === 1" 
                             class="like-avatar single-avatar" 
                             :style="{ backgroundImage: like.likedUsers[0]?.avatarUrl ? `url(${like.likedUsers[0]?.avatarUrl.replace(/`/g, '')})` : '' }">
                            {{ like.likedUsers[0]?.avatarUrl ? '' : like.likedUsers[0]?.username?.charAt(0) }}
                        </div>
                        <!-- 多个点赞用户 -->
                        <div v-else-if="like.likedUsers && like.likedUsers.length > 1" class="multiple-avatars">
                            <div v-for="(user, index) in like.likedUsers.slice(0, 2)" 
                                 :key="user.id" 
                                 class="like-avatar multi-avatar" 
                                 :style="{ backgroundImage: user.avatarUrl ? `url(${user.avatarUrl.replace(/`/g, '')})` : '' }"
                                 @click.stop="goToUserProfile(user.id)">
                                {{ user.avatarUrl ? '' : user.username?.charAt(0) }}
                            </div>
                        </div>
                    </div>
                    <!-- 评论内容 -->
                    <div class="like-content">
                        <div class="like-header">
                            <div class="user-name">
                                <!-- 单个点赞用户 -->
                                <span v-if="like.likedUsers && like.likedUsers.length === 1">{{ like.likedUsers[0]?.username }}</span>
                                <!-- 多个点赞用户 -->
                                <span v-else-if="like.likedUsers && like.likedUsers.length > 1">
                                    {{ like.likedUsers[0]?.username }}、{{ like.likedUsers[1]?.username }}等{{ like.likesCount }}人
                                </span>
                            </div>
                            <div class="like-time">{{ formatTime(like.likeTime) }}</div>
                        </div>
                        <div class="like-text">赞了我的评论</div>
                        <div class="original-post">
                            <div class="post-preview">{{ like.content || '查看原帖' }}</div>
                        </div>
                    </div>
                </div>

                <!-- 视图监听盒子 -->
                <div ref="viewFlagBox_likes" :style="{ paddingTop: likeList.length < 1 ? '20px' : '0px' }">
                    <div v-if="!isHasMoreLikes && !isLoadingLikes" 
                        style="height: 30px;display: flex;justify-content: center;font-size: 12px;color: #61666D;">
                        没有更多获赞记录
                    </div>
                    <div v-else
                        style="height: 30px;display: flex;justify-content: center;font-size: 12px;color: #61666D;">
                        努力加载中
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import 'vant/lib/toast/style'
import api from '@/api/index.js'
import { UserInfoStore } from '@/stores/userInfoStore'
import { TipStore } from '@/stores/tipStore'
import { formatTime } from '@/utils/format.js'

const router = useRouter()
const user_Store = UserInfoStore()
const tip_Store = TipStore()

// #region 辅助方法
// 返回
function GoBack() {
    router.go(-1)
}

// 跳转到帖子详情
function goToPostDetail(postId) {
    router.push({
        name: 'OpusDetail',
        query: { id: postId }
    })
}

// 处理头像点击事件
function handleAvatarClick(likedUsers) {
    if (!likedUsers || likedUsers.length === 0) return;
    
    // 如果只有一个用户，直接跳转到用户主页
    if (likedUsers.length === 1) {
        goToUserProfile(likedUsers[0].id);
        return;
    }
    
    // 如果有多个用户，可以在这里添加更多逻辑，比如显示用户列表弹窗
    // 目前先跳转到第一个用户的主页
    goToUserProfile(likedUsers[0].id);
}

// 跳转用户个人主页
function goToUserProfile(uid) {
    router.push({
        name: 'UserProfile',
        query: { uid: uid }
    })
}
// #endregion


// 获赞记录相关数据和方法
const pageNum_likes = ref(1)
const pageSize_likes = ref(10)
const isLoadingLikes = ref(false)
const isHasMoreLikes = ref(true)
const likeList = ref([])

// 获取获赞记录
const getLikesToMe = async() => {
    try {
        isLoadingLikes.value = true
        const res = await api.Comment_GetLikeToMe(
            pageNum_likes.value,
            pageSize_likes.value
        )
        
        if (res && res.data && res.data.code == 1) {
            const newLikes = res.data.data.list || []
            
            // 如果是第一页，直接替换数据；否则追加数据
            if (pageNum_likes.value == 1) {
                likeList.value = newLikes
            } else {
                likeList.value = [...likeList.value, ...newLikes]
            }
            
            // 判断是否还有更多数据
            // 根据返回的总数和当前已加载数量判断
            const totalCount = parseInt(res.data.data.total) || 0
            isHasMoreLikes.value = likeList.value.length < totalCount
            
        } else {
            tip_Store.errorTip(res?.data?.msg || '获取获赞记录失败')
        }
    } catch (error) {
        console.error('获取获赞记录失败:', error)
        tip_Store.errorTip('获取获赞记录失败，请稍后重试')
    } finally {
        isLoadingLikes.value = false
    }
}

// 加载更多数据
async function loadMoreData() { 
    if(isHasMoreLikes.value===false || isLoadingLikes.value===true){ return }
    console.log('加载更多获赞数据！')
    pageNum_likes.value += 1 // 下一页
    try {
        await getLikesToMe()
    } catch (error) {
        // 如果加载失败，恢复页码
        pageNum_likes.value -= 1
    }
}

// 视图监听相关
const viewFlagBox_likes = ref(null);
let observer = null;

function observerViewFlagBox(){
    observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                console.log('进入视图!!!');
                loadMoreData()
            }
        });
    }, {
        threshold: 0,
        rootMargin: '0px'
    });

    if (viewFlagBox_likes.value) {
        observer.observe(viewFlagBox_likes.value);
    }
}

onMounted(async()=>{
    await getLikesToMe() // 初始化获取获赞记录
    nextTick(() => {
        observerViewFlagBox() // 设置视图监听
    })
})
</script>

<style lang="scss" scoped>
.container {
    background-color: #f8f8f8;
    min-height: 100vh;
}

/* 头部样式 */
.header {
    background: white;
    padding: 15px 20px;
    box-shadow: 0 1px 5px rgba(0,0,0,0.05);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    max-width: 800px;
    margin: 0 auto;
}

.header-left {
    display: flex;
    align-items: center;
}

.back-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
    text-decoration: none;
}

.header-title {
    font-size: 18px;
    font-weight: 500;
    color: #333;
}

/* 主内容样式 */
.main-content {
    margin-top: 54px;
    background: #f8f8f8;
    min-height: calc(100vh - 60px);
}

/* 列表容器样式 */
.list-container {
    padding: 10px 0;
}

/* 获赞项样式 */
.like-item {
    display: flex;
    padding: 15px;
    background: white;
    margin-bottom: 10px;
    cursor: pointer;
    transition: background-color 0.2s;
}

.like-item:hover {
    background-color: #f9f9f9;
}

/* 头像样式 */
.like-avatars {
    position: relative;
    display: flex;
    align-items: center;
    margin-right: 12px;
    min-width: 40px;
    height: 40px;
}

.like-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #f0f0f0;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    color: white;
    border: 2px solid #fff;
    position: relative;
    flex-shrink: 0;
}

.single-avatar {
    position: relative;
}

.multiple-avatars {
    display: flex;
    align-items: center;
}

.multi-avatar {
    position: relative;
    box-shadow: 0 0 0 2px #fff;
}

.multi-avatar:nth-child(2) {
    margin-left: -8px;
    z-index: 1;
}

.multi-avatar:first-child {
    z-index: 2;
}

.like-content {
    flex: 1;
    min-width: 0;
}

.like-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
}

.user-name {
    font-weight: 500;
    color: #333;
    font-size: 14px;
    display: -webkit-box;
    line-clamp: 2;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

.like-time {
    font-size: 12px;
    color: #999;
    min-width: 43px;
}

.like-text {
    font-size: 14px;
    color: #333;
    line-height: 1.4;
    margin-bottom: 8px;
    word-break: break-word;
}

.original-post {
    background-color: #f5f5f5;
    padding: 8px;
    border-radius: 4px;
    margin-top: 8px;
}

.post-preview {
    font-size: 13px;
    color: #666;
    line-height: 1.3;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    line-clamp: 2;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}
</style>